<template>
  <a-modal
    width="80vw"
    :visible="visible"
    title="修改费用"
    :mask-closable="false"
    unmount-on-close
    @before-open="handleBeforeOpen"
    @cancel="handleCancel"
    @before-ok="handleBeforeOk"
  >
    <div style="max-height: 80vh">
      <a-alert class="items-start mb-2">
        <template #icon>
          <icon-exclamation-circle />
        </template>
        <div>1、在此修改实结及已对账金额，不影响结算明细及对账明细</div>
        <div>2、在此修改费项金额会自动重新计算抽佣金额，如手动修改过抽佣金额则不重新计算，以您操作为准</div>
      </a-alert>
      <table-index :table="table" @loadData="loadData">
        <template #amount="{ record }">
          <a-input-number
            v-model="record.amount"
            :precision="2"
            hide-button
            allow-clear
            :min="0"
            :max="99999999.99"
            :error="record.amountError"
            @change="(value: number | undefined) => onChangeAmount(value, record)"
            placeholder="请输入"
          />
          <div class="arco-form-item-message" v-if="record.amountError">{{ amountError }}</div>
        </template>
        <template #payAmount="{ record }">
          <a-input-number
            v-model="record.payAmount"
            :precision="2"
            hide-button
            allow-clear
            :min="0"
            :max="99999999.99"
            :error="record.payAmountError"
            @change="(value: number | undefined) => onChangePayAmount(value, record)"
            placeholder="请输入"
          />
          <div class="arco-form-item-message" v-if="record.payAmountError">{{ payAmountError }}</div>
        </template>
        <template #billedAmount="{ record }">
          <a-input-number
            v-model="record.billedAmount"
            :precision="2"
            hide-button
            allow-clear
            :min="0"
            :max="99999999.99"
            :error="record.billedAmountError"
            @change="(value: number | undefined) => onChangeBilledAmount(value, record)"
            placeholder="请输入"
          />
          <div class="arco-form-item-message" v-if="record.billedAmountError">{{ billedAmountError }}</div>
        </template>
        <template #remark="{ record }">
          <a-input v-model="record.remark" placeholder="请输入" max-length="100" />
        </template>
      </table-index>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
  import { computed, ref } from 'vue'
  import { Message } from '@arco-design/web-vue'

  import { useTable } from '@/hooks/table'
  import { getShortOrdrFeeDetail } from '@/api/order/sOrder'
  import { updateShortOrderBill } from '@/api/finance/examine'

  const props = defineProps({
    modelValue: {
      type: Boolean,
      default: false,
    },
    data: {
      type: Object,
      default: () => ({}),
    },
  })

  const emits = defineEmits(['update:modelValue', 'ok'])

  const table = useTable({
    pagination: false,
    columns: [
      { title: '费用名称', dataIndex: 'itemName', fixed: 'left', width: 80 },
      { title: '费用类型', dataIndex: 'feeTypeName', width: 80 },
      { title: '收支类型', dataIndex: 'costTypeName', width: 80 },
      { title: '总额', dataIndex: 'amount', slotName: 'amount', unit: '元', width: 120 },
      { title: '实结', dataIndex: 'payAmount', slotName: 'payAmount', unit: '元', width: 120 },
      { title: '已对账', dataIndex: 'billedAmount', slotName: 'billedAmount', unit: '元', width: 120 },
      { title: '备注', dataIndex: 'remark', slotName: 'remark', width: 200 },
    ],
  })

  const amountError = ref('')
  const onChangeAmount = (value: number | undefined, record: any) => {
    // payTypeList -1 嘉联聚合支付
    if ([-1].includes(record.payTypeList) && (value == undefined || value < record.amount)) {
      record.amountError = true
      amountError.value = '总额需>=聚合支付金额，请重新输入'
    } else if (value == undefined || value < record.payAmount) {
      record.amountError = true
      amountError.value = '总额需>=实结金额，请重新输入'
    } else {
      record.amountError = false
      amountError.value = ''
    }
  }

  const payAmountError = ref('')
  const onChangePayAmount = (value: number | undefined, record: any) => {
    // payTypeList -1 嘉联聚合支付
    if ([-1].includes(record.payTypeList) && (value == undefined || value < record.amount)) {
      record.payAmountError = true
      payAmountError.value = '实结金额需>=聚合支付金额，请重新输入'
    } else if (value == undefined || value > record.amount) {
      record.payAmountError = true
      payAmountError.value = '实结金额需<=总额，请重新输入'
    } else {
      record.payAmountError = false
      payAmountError.value = ''
    }
  }

  const billedAmountError = ref('')
  const onChangeBilledAmount = (value: number | undefined, record: any) => {
    if (value == undefined || value > record.payAmount) {
      record.billedAmountError = true
      billedAmountError.value = '已对账金额需<=实结金额，请重新输入'
    } else {
      record.billedAmountError = false
      billedAmountError.value = ''
    }
  }

  const visible = computed({
    get: () => props.modelValue,
    set: (value) => emits('update:modelValue', value),
  })

  /**
   * @param id 订单id
   * feeStatus 0 待结算 1 结算中 2 已结算 3 部分结算 9 无需结算 90 已作废
   * billStatus 1 待对账 2 部分对账 3 已对账 9 关闭对账
   * feeType 1 线下费用 2 线上费用
   * orderStatus 10 待排车 100 待用车 200 用车中 300 已还车 1000 已完成 -100 已取消
   */
  const loadData = (id: string | number) => {
    table.tableLoading = true
    getShortOrdrFeeDetail({ id })
      .then((res: any) => {
        table.dataList = res.result
          .map((item: any) => {
            return {
              ...item,
              amountError: false,
              payAmountError: false,
              billedAmountError: false,
            }
          })
          .filter((item: any) => item.feeStatus != 1 && item.feeStatus != 9 && item.feeStatus != 90 && item.billStatus != 9)

        if (props.data.orderStatus != 1000 && props.data.orderStatus != -100) {
          table.dataList = table.dataList.filter((item: any) => !(item.feeType == 2 && item.feeStatus == 0))
        }
      })
      .finally(() => {
        table.tableLoading = false
      })
  }

  const handleBeforeOpen = () => {
    loadData(props.data.id)
  }

  const handleCancel = () => {
    visible.value = false
  }

  const handleBeforeOk = (done: (closed: boolean) => void) => {
    const data = table.dataList.map((item: any) => {
      return {
        id: item.id,
        amount: item.amount,
        payAmount: item.payAmount,
        billedAmount: item.billedAmount,
        remark: item.remark,
      }
    })

    updateShortOrderBill(data)
      .then(() => {
        visible.value = false
        Message.success('修改成功')
        emits('ok')
        done(true)
      })
      .catch(() => {
        done(false)
      })
  }
</script>

<style scoped lang="less"></style>
